<template>
	<div class="container">
		<h3>加载OpenStreet地图</h3>
		<el-button class="btns" @click="beiji">去北京</el-button>
		<el-button class="btns" @click="shangmian">向上移动</el-button>
		<el-button class="btns" @click="switchMapType">
			{{ currentMapType === 'city' ? '切换到卫星图' : '切换到城市图' }}
		</el-button>
		<div id="vue-openlayers" class="map-x"></div>
	</div>
</template>
<script>
	import 'ol/ol.css'
	import {
		Map,
		View
	} from 'ol'
	import Tile from 'ol/layer/Tile'
	import XYZ from 'ol/source/XYZ'

	export default {
		name: 'FirstMap',
		data() {
			return {
				map: null,
				currentMapType: 'city', // 'city' 或 'satellite'
				cityLayer: null,
				satelliteLayer: null
			}
		},
		methods: {
			initMap() {
				this.cityLayer = new Tile({
					source: new XYZ({
						url: 'https://webrd04.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}',
						wrapX: true
					})
				});
				
				this.satelliteLayer = new Tile({
					source: new XYZ({
						url: 'https://webst01.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
						subdomains: ['1', '2', '3', '4'],
						wrapX: true
					}),
					visible: false // 默认不显示
				});
        this.markerSource=new Tile({
          source:new XYZ({
            url:'https://webst01.is.autonavi.com/appmaptile?style=8&x={x}&y={y}&z={z}',
            wrapX:true
          }),
          visible:false
        })
				
				this.map = new Map({
					target: "vue-openlayers",
					layers: [
						this.cityLayer,
						this.satelliteLayer,
            this.markerSource
					],
					view: new View({
						projection: "EPSG:4326",
						center: [114.25, 30.59],
						zoom: 8
					}),
				})
			},
			beiji(){
				if(this.map){
					const view=this.map.getView();
          view.animate({
            center:[116.46,39.93],
            zoom:5,
            duration:3000,
          })
				}
			},
			shangmian(){
				if(this.map) {
					const view=this.map.getView();
					const center=view.getCenter();
					if(center && Array.isArray(center)) {
						center[1]+=0.1;
						view.setCenter(center);
					}
				}
			},
			switchMapType() {
				if (!this.map) return;
				
				if (this.currentMapType === 'city') {
					this.cityLayer.setVisible(false);
					this.satelliteLayer.setVisible(true);
          this.markerSource.setVisible(true);
					this.currentMapType = 'satellite';
				} else {
					this.satelliteLayer.setVisible(false);
          this.markerSource.setVisible(false);
					this.cityLayer.setVisible(true);
					this.currentMapType = 'city';
				}
			}
		},
		mounted() {
			this.initMap();
		}
	}
</script>

<style scoped>
	#vue-openlayers {
		width: 1500px;
		height: 1000px;
		margin: 0 auto;
		border: 1px solid #42B983;
	}
	h3 {
		line-height: 40px;
	}
	.btns{
        flex: auto;
        top: 10px;
        left: 10px;
        margin: 5px;
    }
</style>